<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>享元模式</title>
</head>
<body>
<script>
// 健康测量
function Human(sex) {
    this.sex = sex;
}
// 开始评判
Human.prototype.start = function(name) {
    // 操作前先更新当前状态（从外部状态管理器中获取）
    HumanManager.updateFitnessData(name, this);

    var ret = name + ': ';

    if (this.sex === 'T1') {
        ret += this.getMsgT1();
    } else if(this.sex === 'T2') {
        ret += this.getMsgT2();
    }

    console.log(ret);
};

// 男性评判规则
Human.prototype.getMsgT1 = function() {
    var ratio = this.height / this.weight;

    return this.age > 20 ? (ratio > 3.5) : (ratio > 2.8);
};

// 女性评判规则
Human.prototype.getMsgT2 = function() {
    var ratio = this.height / this.weight;
    
    return this.age > 20 ? (ratio > 4) : (ratio > 3);
};

// 工厂,创建可共享的对象
//
var HumanFactory = {
    objs: {},
    create: function(sex) {
        if (!this.objs[sex]) {
            this.objs[sex] = new Human(sex);
        }

        return this.objs[sex];
    }
};

// 管理器，管理非共享的部分
var HumanManager = {
    allHumanData: {},//保存所有子类的信息
    
    // 添加一项
    add: function(name, sex, age, height, weight) {
        var fitness = HumanFactory.create(sex);
        
        // 存储变化的数据
        this.allHumanData[name] = {
            age: age,
            height: height,
            weight: weight
        };

        return fitness;
    },
    
    // 从存储的数据中获取，更新至当前正在使用的对象
    updateFitnessData: function(name, obj) {
        var allHumanData = this.allHumanData[name];

        for (var item in allHumanData) {
            if (allHumanData.hasOwnProperty(item)) {
                obj[item] = allHumanData[item];
            }
        }
    }
};




var a = HumanManager.add('A', 'T1', 18, 160, 80);
var b = HumanManager.add('B', 'T1', 21, 180, 70);
var c = HumanManager.add('C', 'T2', 28, 160, 80);
var d = HumanManager.add('D', 'T2', 18, 170, 60);
var e = HumanManager.add('E', 'T2', 18, 160, 40);

console.log('HumanFactory 1', JSON.parse(JSON.stringify(HumanFactory)));//objs:{T1: {sex: "T1"},T2: {sex: "T2"}}
console.log('HumanManager 1', JSON.parse(JSON.stringify(HumanManager)));

// 开始评判
a.start('A'); // A: false
b.start('B'); // B: false
c.start('C'); // C: false
d.start('D'); // D: false
e.start('E'); // E: true

console.log('HumanFactory 2', JSON.parse(JSON.stringify(HumanFactory)));
//T1: {sex: "T1", age: 21, height: 180, weight: 70}
//T2: {sex: "T2", age: 18, height: 160, weight: 40}
console.log('HumanManager 2', JSON.parse(JSON.stringify(HumanManager)));
</script>
</body>
</html>